import { _decorator, Component, Node, Prefab, instantiate, view, Camera, Sprite, Color, Collider2D, isValid, math, RigidBody2D, Widget, UITransform, find } from 'cc';
import { Brick } from './Brick';
const { ccclass, property } = _decorator;

@ccclass('BrickManager')
export class BrickManager extends Component {
    private static instance: BrickManager = null;

    @property(Prefab)
    brickPrefab:Prefab = null;

    @property
    InitPosX:number = 0;
    @property
    InitPosY:number = 0;

    @property
    rowCount: number = 0; // 行数

    @property
    columnCount: number = 0; // 列数

    @property
    xOffset: number = 77; // X 方向偏移量

    @property
    yOffset: number = 33; // Y 方向偏移量

    enemyWidth:number = 0;
    enemyHeight:number = 0;

    brickNodeList:(Node | null)[] = new Array(this.rowCount*this.columnCount).fill(null); 


    startTimer:number = 0;
    endTimer:number = 1000;
    
    onLoad() {
        if (BrickManager.instance === null) 
        {
            BrickManager.instance = this;
        } else {
            console.error("BrickManager 已存在，请确保场景中只有一个 BrickManager");
            this.node.destroy();
        }
    }

    start() {
    }

    update(deltaTime: number) {
        if(this.startTimer > 0 && new Date().getTime() - this.startTimer >= this.endTimer)
        {
            // 2D 碰撞体
            const colliders2D = this.node.getComponentsInChildren(Collider2D);
            colliders2D.forEach(collider => {
                collider.enabled = true;
            });

            const rigidBodies = this.node.getComponentsInChildren(RigidBody2D);
            rigidBodies.forEach(body => {
                body.enabled = true;
            });

            this.startTimer = 0;
        }
    }

    protected onEnable() {
        window.addEventListener('resize', this.onResize.bind(this));
    }
    
    protected onDisable() {
        window.removeEventListener('resize', this.onResize.bind(this));
    }

    private onResize() {
        this.calBrickSize();

        if(this.updateFirst())
        {
            //延迟1帧绘制其它砖块
            this.scheduleOnce(() => {
                this.updateExistingBricks();
            });
        }
    }

    updateFirst():boolean
    {
        const firstBrick = this.brickNodeList[0];
        if (firstBrick == null) 
            return false;

        // 设置 enemy 大小
        const enemyTransform = firstBrick.getComponent(UITransform);
        if (enemyTransform) {
            enemyTransform.width = this.enemyWidth;
            enemyTransform.height = this.enemyHeight;
        }
        //const widget = firstBrick.getComponent(Widget);
        //if (widget) {
        //    widget.updateAlignment();
        //}

        return true;
    }

    private updateExistingBricks() {
        const firstBrick = this.brickNodeList[0];
        if(firstBrick == null)
        {
            console.error("drawAllBrick Fail , Can Not Get First Brick");
            return;
        }

        //获取起始位置
        let startX = firstBrick.position.x;
        let startY = firstBrick.position.y;

         let brick_id = 1;
        for (let row = 0; row < this.rowCount; row++) {
            for (let col = 0; col < this.columnCount; col++) {
                if(row <= 0 && col <= 0)
                {
                    continue; //忽略第一个
                }
                const enemy = this.brickNodeList[brick_id];
                if(enemy)
                {
                    const posX = startX + col * this.xOffset;
                    const posY = startY - row * this.yOffset;
                    enemy.setPosition(posX, posY, 0);

                     // 设置 enemy 大小
                    const enemyTransform = enemy.getComponent(UITransform);
                    if (enemyTransform) {
                        enemyTransform.width = this.enemyWidth;
                        enemyTransform.height = this.enemyHeight;
                    }
                }

                brick_id += 1;
            }
        }
    }

    public getAllBrickNum():number
    {
        return this.rowCount*this.columnCount;
    }

    public reset() {
        // 重置单例类的状态
        BrickManager.instance = null;
    }

    public static getInstance(): BrickManager {
        return BrickManager.instance;
    }
    
    calBrickSize()
    {
        const canvas = find('Canvas');
        const canvasTransform = canvas.getComponent(UITransform);
        const canvasWidth = canvasTransform.width;
        console.log("Canvas  weight : ",canvasWidth," Height : ",canvasTransform.height)
        // 1. 计算可用宽度（左右留 5% 边距）
        const marginRatio = 0.03;
        const availableWidth = canvasWidth * (1 - 2 * marginRatio);

        // 2. 计算 Enemy 宽度（刚好放满 columnCount 个）
        this.enemyWidth = availableWidth / this.columnCount;

        // 3. 如果 Enemy 太小，减少数量
        const minEnemyWidth = 100; // 最小宽度
        if (this.enemyWidth < minEnemyWidth) {
            this.columnCount = Math.floor(availableWidth / minEnemyWidth);
            this.enemyWidth = availableWidth / this.columnCount;
        }

        // 4. 计算 Enemy 高度（按比例）
        this.enemyHeight = this.enemyWidth * 0.5;

        // 5. 更新间距（10% 的 Enemy 宽度）
        this.xOffset = this.enemyWidth * 1.01;
        this.yOffset = this.enemyHeight * 1.1;

        console.log(`Enemy 大小: ${this.enemyWidth}x${this.enemyHeight}`);
        console.log(`每排 Enemy 数量: ${this.columnCount}`);
    }

    setBrickAttr(brickNode:Node,brickID:number)
    {
        // 设置 enemy 大小
        const enemyTransform = brickNode.getComponent(UITransform);
        if (enemyTransform) {
            enemyTransform.width = this.enemyWidth;
            enemyTransform.height = this.enemyHeight;
        }

        const BrickNode = brickNode.getComponent(Brick);
        if (BrickNode) {
            BrickNode.setBrickID(brickID);
        }

        const collider = brickNode.getComponent(Collider2D);
        collider.enabled = false;
        const rigidBody = brickNode.getComponent(RigidBody2D);
        rigidBody.enabled = false;

        this.node.addChild(brickNode);
        this.brickNodeList[brickID] = brickNode;
    }
    
    drawFirst()
    {
        const enemy = instantiate(this.brickPrefab);
        if(enemy == null)
        {
            console.error("Create Brick Fail");
            return;
        }

        const canvas = find('Canvas');
        const canvasTransform = canvas.getComponent(UITransform);
        const canvasWidth = canvasTransform.width;
        const canvasHeight = canvasTransform.height;

        // 动态计算初始位置 (5% 的边距)
        const marginLeft = canvasWidth * 0.03;
        const marginTop = canvasHeight * 0.185;

        const nodeWidget = enemy.addComponent(Widget);
        nodeWidget.isAlignTop = true;
        nodeWidget.top = marginTop;
        nodeWidget.isAlignLeft = true;
        nodeWidget.left = marginLeft;

        this.setBrickAttr(enemy,0);
    }

    drawAllBrick()
    {
        const firstBrick = this.brickNodeList[0];
        if(firstBrick == null)
        {
            console.error("drawAllBrick Fail , Can Not Get First Brick");
            return;
        }

        //获取起始位置
        let startX = firstBrick.position.x;
        let startY = firstBrick.position.y;

         let brick_id = 1;
        for (let row = 0; row < this.rowCount; row++) {
            for (let col = 0; col < this.columnCount; col++) {
                if(row <= 0 && col <= 0)
                {
                    continue; //忽略第一个
                }

                const enemy = instantiate(this.brickPrefab);
                if(enemy)
                {
                    const posX = startX + col * this.xOffset;
                    const posY = startY - row * this.yOffset;
                    enemy.setPosition(posX, posY, 0);

                    this.setBrickAttr(enemy,brick_id);
                    
                    brick_id += 1;
                }
                else
                {
                    console.error("Create Brick Fail");
                }
                
            }
        }
    }

    public GameLoad() {
        //动态计算方块大小
        this.calBrickSize();

        this.drawFirst();

        //延迟1帧绘制其它砖块
        this.scheduleOnce(() => {
            this.drawAllBrick();
        });
    }

    public GameOver()
    {
        this.node.removeAllChildren();
        for (let index = 0; index < this.brickNodeList.length; index++) {
            const element = this.brickNodeList[index];
            if(element)
            {
                element.destroy();
            }
        }

        this.brickNodeList.fill(null);
    }

    // 移动所有砖块向下一个节点长度的距离
    public moveBricksDown() {
        for (let index = 0; index < this.brickNodeList.length; index++) {
            const brickNode = this.brickNodeList[index];
            if (brickNode && isValid(brickNode)) {
                const currentPos = brickNode.position;
                const newPosY = currentPos.y - Math.floor(this.yOffset/2); // 向下移动一个节点长度的距离
                brickNode.setPosition(currentPos.x, newPosY, currentPos.z);
            }
        }
    }

    public GameStart()
    {
        this.startTimer = new Date().getTime();
    }
}


